package com.example.permissionservice.service;

import com.myprojects.common.pojo.Resource;
import com.myprojects.common.pojo.UserWithRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class UserDetailServiceImp implements UserDetailsService {

    @Autowired
    private UserWithRoleService userWithRoleService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//        //先查找出用户信息和用户权限
//        UserWithRole user = userWithRoleService.selectByUsername(s);
//        List<Resource> resources = permissionService.getByUsername(s);
//        List<SimpleGrantedAuthority> transformedAuthorities = null;//UserDetails接口要求权限list
//
//        //对用户权限进行封装，使用iterator遍历自定义的权限list并生成新的权限
//        transformedAuthorities = new ArrayList<>();
//        Iterator<Resource> iterator = resources.listIterator();
//        while (iterator.hasNext()){
//            Resource resource = iterator.next();
//            transformedAuthorities.add(new SimpleGrantedAuthority(resource.getResource_name()));
//        }
//
//        // 返回封装的UserDetails用户详情类
//        if(user != null){
//            UserDetails userDetails = new org.springframework.security.core.userdetails.
//                    User(user.getUsername(),user.getPassword(),transformedAuthorities);
//            return userDetails;
//        } else {
//            // 如果查询的用户不存在（用户名不存在），必须抛出此异常
//            throw new UsernameNotFoundException("当前用户不存在！");
//        }
        return null;
    }

//    String accessFunction(Authority authority) {
//        return authority.getAuthority();
//    }
}
